package com.earthea.datasource.lock;

import com.earthea.api.lock.AbstractLock;

public class LockInMysql extends AbstractLock {

    private final LockRepository lockRepository;

    public LockInMysql(String lockId, long timeout, LockRepository lockRepository) {
        super(lockId, timeout);
        this.lockRepository = lockRepository;
        lockRepository.create();
    }

    @Override
    public boolean tryLock() {
        boolean isGet = lockRepository.tryLock(lockId, timeout);
        if (isGet) {
            return true;
        } else {
            boolean isTimeout = lockRepository.isTimeout(lockId);
            if (isTimeout) {
                this.unlock();
                isGet = lockRepository.tryLock(lockId, timeout);
            }
            return isGet;
        }
    }

    @Override
    public void unlock() {
        lockRepository.unLock(lockId);
    }
}
